<template>
  <tm-app ref="app" style="overflow-x: hidden">
    <!-- 返回图标/tags/搜索 -->
    <directoryTags
      :currentDirectoryName="currentDirectoryName"
      :showBack="data.focusFile || data.parentList != undefined"
      :taglist="data.taglist"
      :tagActive="data.tagActive"
      :menuShow="data.focusFile"
      :isSelectable="isSelectable"
      @btnClick="changeTags"
      @searchClick="changeSearchClick"
      @searchFlags="searchFlags"
      @goBack="goBack"
      @goMenu="goMenu"
      @changeSelectable="changeSelectable"
    ></directoryTags>
    <!-- 目录/文件列表 -->
    <directoryFiles
      v-show="data.focusFile"
      :isSelectable="isSelectable"
      :superior="(data.superior as IDEntity)"
      :superiorType="true"
      :setList="data.files.filter(filterExp).filter(tagFilter)"
      ref="filesRef"
      @changeSuperior="changeSuperior"
      @updateSetList="updateSetList"
      @refresh="focusHanlder"
      @changeHierarchyName="changeHierarchyName"
      @selectionComplete="selectionComplete"
      @changeSelectable="changeSelectable"
    ></directoryFiles>
    <!-- 单位/数据核列表 -->
    <directoryViewer
      v-show="!data.focusFile"
      :searchFlag="searchFlag"
      :setList="data.list.filter(filterExp).filter(tagFilter)"
      @btnClick="focusHanlder"
    ></directoryViewer>
    <view
      v-if="showGuide"
      class="guide-mask"
      :style="{
        '-webkit-mask-size':
          currentStep === steps.length - 1
            ? '60rpx 90rpx, 100%'
            : '600rpx 90rpx, 100%',
        '-webkit-mask-position':
          currentStep === steps.length - 1
            ? '664rpx 240rpx, 0'
            : '28rpx 240rpx, 0',
        maskSize:
          currentStep === steps.length - 1
            ? '60rpx 90rpx, 100%'
            : '600rpx 90rpx, 100%',
        maskPosition:
          currentStep === steps.length - 1
            ? '664rpx 240rpx, 0'
            : '28rpx 240rpx, 0'
      }"
    >
      <view
        class="guide-dialog"
        :style="{
          left: currentStep === steps.length - 1 ? 'auto' : '20rpx',
          right: currentStep === steps.length - 1 ? '20rpx' : 'auto'
        }"
      >
        <view
          class="diamond"
          :style="{
            left: currentStep === steps.length - 1 ? 'auto' : '20rpx',
            right: currentStep === steps.length - 1 ? '20rpx' : 'auto'
          }"
        ></view>
        <text class="guide-tip">{{ steps[currentStep].tip }}</text>
        <button class="guide-button" @click="nextStep">
          {{
            currentStep === steps.length - 1
              ? '完成'
              : `下一步 ${currentStep + 1}/${steps.length}`
          }}
        </button>
      </view>
    </view>
  </tm-app>
</template>
<script lang="ts" setup>
import { onShow } from '@dcloudio/uni-app'
import orgCtrl from '@/ts/controller'
import { reactive, ref, onMounted } from 'vue'
import directoryViewer from '@/components/Directory/views.vue'
import directoryTags from '@/components/Directory/tags.vue'
import directoryFiles from '@/components/Directory/files.vue'
import { IFile, IDEntity, IContainer } from '@/ts/core'
onShow(() => {
  getList()
})
const data = reactive<{
  list: any[]
  focusFile: boolean
  files: any[]
  taglist: any[]
  tagActive: string
  searchVal: string
  superior?: IDEntity
  parentList?: IDEntity
}>({
  list: [],
  focusFile: false,
  taglist: [],
  files: [],
  tagActive: '全部',
  searchVal: '',
  superior: undefined,
  parentList: undefined
})
const showGuide = ref(false) // 是否显示引导
const currentStep = ref(0) // 当前步骤
const isUpdating = ref(false)
const isSelectable = ref(false)

const currentDirectoryName = ref<string>('数据')
const filesRef = ref()
const searchFlag = ref(false)
// 引导的步骤内容
const steps = ref([
  {
    tip: '点击此区域查看所属文件'
  },
  {
    tip: '查看下一级内设机构/群组'
  }
])
// 判断是否需要显示引导
onMounted(() => {
  const isGuideShown = uni.getStorageSync('guide_shown')
  if (!isGuideShown) {
    showGuide.value = true
  }
})
// 切换到下一步
const nextStep = () => {
  if (currentStep.value < steps.value.length - 1) {
    currentStep.value++
  } else {
    showGuide.value = false
    uni.setStorageSync('guide_shown', true) // 保存引导状态
  }
}
const changeSelectable = (val: boolean) => {
  isSelectable.value = val
}
const focusHanlder = async (
  file: IFile | undefined,
  type: string,
  isReload: boolean = false
) => {
  if (isUpdating.value) return // 检查标志
  isUpdating.value = true // 设置为正在更新
  uni.showLoading({ title: '加载中...' })
  data.superior = undefined
  // 防止重复设置焦点
  if (file && file.key && type == 'disk') {
    data.focusFile = true
    try {
      await file.directory.loadContent(isReload) // 加载内容
      data.files = file.directory.content()
      changeHierarchyName(file.name)
      data.taglist = groupTags(data.files)
      if (data.parentList) {
        data.parentList = file
      }
    } catch (error) {
      console.error('加载内容失败', error)
    }
  }
  if (file && file.key && type == 'colony') {
    data.focusFile = false
    data.parentList = file
    data.list = file.content()
    data.taglist = groupTags(data.list)
  }
  uni.hideLoading()
  isUpdating.value = false // 更新结束
}
//修改当前层级名称
const changeHierarchyName = (name: string) => {
  currentDirectoryName.value = name
}
const updateSetList = (newList: IDEntity[]) => {
  data.files = newList
  data.taglist = groupTags(data.files)
}
const changeSuperior = (file: IDEntity) => {
  data.superior = file
}
//返回上一级
const goBack = () => {
  if (!data.superior) {
    data.focusFile = false
    data.files = []
    data.parentList = (data.parentList as IContainer)?.groupTags.some(
      i => i.includes('单位') || i.includes('人员') || i.includes('本人')
    )
      ? undefined
      : (data.parentList as IContainer)?.superior
    if (!data.parentList) {
      getList()
    } else {
      data.list = (data.parentList as IContainer).content()
      data.taglist = groupTags(data.list)
    }
  } else if (
    data.superior &&
    'isContainer' in data.superior &&
    data.superior.isContainer
  ) {
    data.files = (data.superior as IContainer)?.directory.content()
    data.taglist = groupTags(data.files)
    data.superior = (data.superior as IContainer)?.superior.groupTags.some(
      i => i.includes('单位') || i.includes('人员') || i.includes('本人')
    )
      ? undefined
      : (data.superior as IContainer)?.superior
  }
}
const changeTags = (tag: any) => {
  data.tagActive = tag.tag
}
const searchFlags = (flags: boolean) => {
  searchFlag.value = flags
}
const changeSearchClick = (val: string) => {
  data.searchVal = val
}
const filterExp = (file: IDEntity) => {
  const filters = data.searchVal
    .split('$$')
    .filter(item => item && item.length > 1)
  return (
    filters.length < 1 ||
    filters.some(
      item =>
        file.code?.includes(item) ||
        file.name.includes(item) ||
        file.remark.includes(item) ||
        file.typeName.includes(item) ||
        file.filterTags.filter(i => i.includes(item)).length > 0 ||
        file.groupTags.filter(i => i.includes(item)).length > 0
    )
  )
}
const tagFilter = (file: IDEntity) => {
  let success = true
  if (data.tagActive !== '全部') {
    success = file.filterTags.includes(data.tagActive)
  } else {
    success = !file.filterTags.includes('已删除')
  }
  return success
}
const groupTags = (data: any) => {
  const tags = ['全部'].map(tag => {
    return { tag, count: 0 }
  })
  data.forEach((entity: any) => {
    entity.filterTags.forEach((tag: string) => {
      const index = tags.findIndex(i => i.tag === tag)
      if (index > -1) {
        tags[index].count += 1
      } else {
        tags.push({ tag, count: 1 })
      }
    })
  })

  return tags.sort((a, b) => {
    const aqz = a.tag === '已删除' ? 10 : 0
    const bqz = b.tag === '已删除' ? 10 : 0
    return aqz - bqz
  })
}
const goMenu = (firstMenuItem: string, secondMenuItem?: string) => {
  if (!filesRef.value) return
  //1级菜单firstMenuItem，2级菜单secondMenuItem
  filesRef.value.filesMenu(firstMenuItem, secondMenuItem)
}
//选择的文件项
const selectionComplete = (indexes: number[], files: IFile[]) => {
  console.log('选择完成', indexes, files)
}
async function getList() {
  uni.showLoading({ title: '加载中...' })
  await orgCtrl.user.loadTeams()
  uni.hideLoading()
  data.list = [orgCtrl.user, ...orgCtrl.user.companys]
  if (
    data.taglist.length == 0 ||
    (!data.superior && !data.focusFile && data.taglist.length > 0)
  ) {
    data.taglist = groupTags(data.list)
  }
}
</script>
<style scoped>
.guide-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  mask-image: linear-gradient(red, red), linear-gradient(red, red);
  mask-repeat: no-repeat;
  mask-composite: exclude;
  backdrop-filter: blur(4rpx);
}

.guide-dialog {
  background: white;
  border-radius: 24rpx;
  padding: 32rpx;
  width: 80%;
  box-shadow: 0px 8rpx 16rpx rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 360rpx;
  height: 108rpx;
}

.guide-tip {
  font-size: 14px;
  color: #333;
  margin: 32rpx 0;
}

.guide-button {
  width: 35%;
  background: #007aff;
  color: white;
  border: none;
  padding: 8rpx 32rpx;
  border-radius: 16rpx;
  font-size: 14px;
  position: absolute;
  right: 20rpx;
}
.diamond {
  width: 32rpx;
  height: 32rpx;
  background: white;
  transform: rotate(45deg);
  position: absolute;
  top: -16rpx;
}
</style>
